<?php
namespace app\lmsx\model;

use think\Model;
use traits\model\SoftDelete;
use util\Tree;
use think\Db;

/**
 * 文章分类模型
 * @author lan
 */
class Category extends Model
{
    use SoftDelete;
    protected $table = 'dp_lmsx_category';
    protected $autoWriteTimestamp = true;

    //获取分类选择菜单
    public static function getArticleList(){
        $where['status']=1;
        $menu=Db::table('dp_lmsx_category')->where($where)->order('id,sort desc')->column('id,name');
        if(empty($menu))$menu[0]='暂无分类';
        return $menu;
        //dump($menu);
    }


    /**
     * 获取树状栏目
     * @param int $id 需要隐藏的栏目id
     * @param string $default 默认第一个节点项，默认为“顶级栏目”，如果为false则不显示，也可传入其他名称
     * @param string $ident 分类的唯一标识 article/文章分类 datum/资料分类
     * @return array|mixed
     */
    public static function getTreeList($id = 0, $default = '',$ident='article')
    {
        $result[0] = '顶级栏目';

        // 排除指定节点及其子节点
        if ($id !== 0) {
            $hide_ids = array_merge([$id], self::getChildsId($id));
            $where['id'] = ['notin', $hide_ids];
        }

        $where['ident']=$ident;

        $data_list = Tree::config(['title' => 'name'])->toList(Db::table('dp_lmsx_category')->where($where)->order('pid,id')->column('id,pid,name'));
        foreach ($data_list as $item) {
            $result[$item['id']] = $item['title_display'];
        }

        // 设置默认节点项标题
        if ($default != '') {
            $result[0] = $default;
        }

        // 隐藏默认节点项
        if ($default === false) {

            unset($result[0]);
        }
       //$result[0]=$default;
        //dump($result);die;
        return $result;
    }

    /**
     * 获取所有子栏目id
     * @param int $pid 父级id
     * @return array
     */
    public static function getChildsId($pid = 0,$ident='')
    {
        $map=['pid'=>$pid];
        if($ident!='') $map['ident']=$ident;
        $ids = self::where($map)->column('id');
        foreach ($ids as $value) {
            $ids = array_merge($ids, self::getChildsId($value));
        }
        return $ids;
    }

    /**
     * 获取资料某一级分类
     */
    public static function getGrade($pid=null){
        if($pid!==null){
            $map=['ident'=>'datum','pid'=>$pid];
        }else{
            $map=true;
        }
        $list=Db::table('dp_lmsx_category')->where($map)->column('id,name');
        $list=['初一'=>'初一','初二'=>'初二','初三'=>'初三','高一'=>'高一','高二'=>'高二','高三'=>'高三'];
        //dump($list);die;
        return $list;
    }
    /**
     * 获取某一级的子分类栏目一维数组
     */
    public static function getDownChild($pid=0,$ident=''){
        $map[]=$pid;
        $map=[
            'pid'=>$pid,
            'ident'=>$ident,
        ];
//        $list=Db::table('dp_lmsx_category')->where($map)->field('id')->select();
//        $ids=[];
//        foreach ($list as $v){
//            $ids[]=$v['id'];
//        }
        $list=Db::table('dp_lmsx_category')->where($map)->column('id,name');
        //dump($list);die;
        return $list;
    }

}
